package com.tubeonfire.model;

import java.util.List;

import javax.jdo.PersistenceManager;

import javax.jdo.Query;
import com.tubeonfire.entity.Tube;

public class TubeModel {

	static PersistenceManager pm = PMF.get().getPersistenceManager();
	
	public static void initPm() {
		if (pm.isClosed()) {
			pm = PMF.get().getPersistenceManager();
		}
	}

	public static boolean add(Tube tube) {
		initPm();
		try {			
			pm.makePersistent(tube);
		} catch (Exception e) {
			System.out.println("Error when add tube object.");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean addAll(List<Tube> listTube) {
		initPm();
		try {
			pm.makePersistentAll(listTube);
			System.out.println("Add all tube success.");
		} catch (Exception e) {
			System.out.println("Error when add many tube object.");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean update(Tube tube) {
		initPm();
		pm.makePersistent(tube);		
		return true;
	}

	@SuppressWarnings("unchecked")
	public static Tube getByTubeId(String tubeId) {
		initPm();
		Tube tube01 = null;
		Query query = pm.newQuery(Tube.class);
		query.setFilter("tubeId==tubeIdPara");
		query.declareParameters("java.lang.String tubeIdPara");
		query.setRange(0, 1);
		List<Tube> listResult = (List<Tube>) query.execute(tubeId);
		if (listResult.size() > 0) {
			tube01 = listResult.get(0);
		}
		return tube01;
	}

	public static void closePM() {
		pm.close();		
	}

}
